﻿@{
    ViewBag.Title = "BillForm";
    Layout = "~/Views/Shared/_OrderForm.cshtml";
}@using LeSoft.Application.Code;
<script>
    var _organizeid = "@OperatorProvider.Provider.Current().CompanyId";
    var keyValue = request('keyValue');
    var TypeName = "";
    var Index = "";
    $(function () {
        InitialPage();
        GetOrderEntryGrid();
        InitControl();
    });
    //初始化页面
    function InitialPage() {
        $(".bills").height($(window).height() - 88);
        //resize重设(表格、树形)宽高
        $(window).resize(function (e) {
            window.setTimeout(function () {
                $('#gridTable').setGridWidth(($('.gridPanel').width()));
                $(".bills").height($(window).height() - 88);
            }, 200);
            e.stopPropagation();
        });
    }
    //初始化控件
    function InitControl() {
        var Mode = "@ViewBag.Mode";
        if (Mode == "True") {
            $("#Code").attr("placeholder", "系统已启用自动编号").attr("disabled", "disabled");
        } else {
            $("#Code").attr("isvalid", "yes").attr("checkexpession", "NotNull").attr("placeholder", "请输入编号");
        }
        //入仓类型
        $("#Type").ComboBoxTree({
            url: "../../SystemManage/DataItemDetail/GetDataItemTreeJson?Encode=WarehousingCategory",
            description: "==请选择==",
            height: "150px",
            click: function (item) {
                TypeName = item.text;
            }
        });
        $("#OrganizeId").ComboBoxSetValue(_organizeid);
        //发票类型
        $("#InvoiceType").ComboBoxTree({
            url: "../../SystemManage/DataItemDetail/GetDataItemTreeJson?Encode=InvoiceType",
            description: "==请选择==",
            height: "150px"
        });
        var queryJson = {};
        if (!!_organizeid)
            queryJson = { "OrganizeId": _organizeid };
        //仓库名称
        $("#WarehouseId").ComboBoxTree({
            url: "../../ResourceManage/RS_Warehouse/GetWarehouseInfoTree?queryJson=" + JSON.stringify(queryJson),
            description: "==请选择==",
            height: "150px",
            click: function (item) {
                _organizeid = item.OrganizeId;
            }
        });
        //是否签名
        $("#IsSign").ComboBox({
            data: [{ "key": "1", "value": "是" }, { "key": "0", "value": "否" }],
            id: "key",
            text: "value",
            description: "=是否签名=",
            click: function (item) {
                if ($("#IsSign").attr("data-value") == 1) {
                    $(".CS_Sign").removeAttr("hidden");
                    $(".CS_Sign input").attr("isvalid", "yes").attr("checkexpession", "NotNull");
                }
                else {
                    $(".CS_Sign").attr("hidden", "hidden");
                    $(".CS_Sign input").removeAttr("isvalid").removeAttr("checkexpession");
                }
            }
        });
        $("#IsSign").ComboBoxSetValue("0");
        //是否结算
        $("#IsSettlement").ComboBox({
            data: [{ "key": "1", "value": "是" }, { "key": "0", "value": "否" }],
            id: "key",
            text: "value",
            description: "=是否结算=",
            click: function (item) {
                if ($("#IsSettlement").attr("data-value") == 1) {
                    $(".CS_Settlement").removeAttr("hidden");
                    $(".CS_Settlement input").attr("isvalid", "yes").attr("checkexpession", "NotNull");
                }
                else {
                    $(".CS_Settlement").attr("hidden", "hidden");
                    $(".CS_Settlement input").removeAttr("isvalid").removeAttr("checkexpession");
                }
            }
        });
        //是否验收
        $("#IsCheck").ComboBox({
            data: [{ "key": "1", "value": "是" }, { "key": "0", "value": "否" }],
            id: "key",
            text: "value",
            description: "=是否验收=",
            click: function (item) {
                if ($("#IsCheck").attr("data-value") == 1) {
                    $(".CS_Check").removeAttr("hidden");
                    $(".CS_Check input").attr("isvalid", "yes").attr("checkexpession", "NotNull");
                }
                else {
                    $(".CS_Check").attr("hidden", "hidden");
                    $(".CS_Check input").removeAttr("isvalid").removeAttr("checkexpession");
                }
            }
        });
        //获取表单
        if (!!keyValue) {
            $.SetForm({
                url: "../../ResourceManage/RS_ProductIn/GetBillInfo",
                param: { keyValue: keyValue },
                success: function (data) {
                    if (data.BillInfo.IsCheck == 1) {
                        $(".CS_Check").removeAttr("hidden");
                    }
                    if (data.BillInfo.IsSettlement == 1) {
                        $(".CS_Settlement").removeAttr("hidden");
                    }
                    if (data.BillInfo.IsSign == 1) {
                        $(".CS_Sign").removeAttr("hidden");
                    }
                    if (data.BillInfo.IsAudit == 1) {
                        $("#Audit").css({ "backgroundColor": "#FFF29D" });
                        var str = "审核人：" + data.BillInfo.AuditUserName + "&nbsp;&nbsp;审核日期：" + data.BillInfo.AuditDate + "&nbsp;&nbsp;审核说明：" + data.BillInfo.AuditMemo;
                        $("#Audit").html(str);
                    }
                    $("#form1").SetWebControls(data.BillInfo);
                    var datalist = data.BillList;
                    var Indx = datalist.length - $("#gridTable").jqGrid("getRowData").length;
                    if (Indx >= 0) {
                        //自动添加行
                        for (var i = 0; i < Indx; i++) {
                            li_AddRow();
                        }
                        li_AddRow();
                    }
                    var $grid = $("#gridTable");
                    //合计
                    var TotalQty = 0.00, TotalAmount = 0.00, TotalTaxAmount = 0.00, TotalCAmount = 0.00;
                    for (var i = 1; i <= datalist.length; i++) {
                        var $Price = datalist[i - 1].UnitPrice / (1 + (datalist[i - 1].Tax / 100));
                        var $Amount = toDecimal(datalist[i - 1].Num * $Price);
                        var $CAmount = toDecimal(datalist[i - 1].Price - $Amount);
                        TotalQty += Number(datalist[i - 1].Num);
                        TotalAmount += Number($Amount);
                        TotalTaxAmount += Number(datalist[i - 1].Price);
                        TotalCAmount += Number($CAmount);
                        debugger;
                        var $ellipsis = $('#' + i);
                        $ellipsis.find('input[name="OrderEntryId"]').val(datalist[i - 1].Id);
                        $ellipsis.find('input[name="ProductName"]').val(datalist[i - 1].Name);
                        $ellipsis.find('input[name="ProductCode"]').val(datalist[i - 1].Code);
                        $ellipsis.find('input[name="ProductId"]').val(datalist[i - 1].ProductId);
                        $ellipsis.find('input[name="ModelNo"]').val(datalist[i - 1].ModelNo);
                        $ellipsis.find('input[name="Brand"]').val(datalist[i - 1].Brand);
                        $ellipsis.find('input[name="Usememo"]').val(datalist[i - 1].UseMemo);
                        $ellipsis.find('input[name="OverdueDate"]').val(datalist[i - 1].OverdueDate);
                        $ellipsis.find('input[name="Unit"]').val(datalist[i - 1].Unit);
                        $ellipsis.find('input[name="TaxUnitPrice"]').val(datalist[i - 1].UnitPrice);
                        $ellipsis.find('input[name="Tax"]').val(datalist[i - 1].Tax);
                        $ellipsis.find('input[name="Price"]').val(toDecimal($Price));
                        $ellipsis.find('input[name="Qty"]').val(datalist[i - 1].Num);
                        $ellipsis.find('input[name="CAmount"]').val($CAmount);
                        $ellipsis.find('input[name="TaxAmount"]').val(datalist[i - 1].Price);
                        $ellipsis.find('input[name="Amount"]').val($Amount);
                        $ellipsis.find('input[name="Description"]').val(datalist[i - 1].Description);
                        //$ellipsis.find('.decimal').keyup();
                    }
                    if (!!TotalQty && TotalQty != 0)
                        $("#TotalQty").text(toDecimal(TotalQty));   
                    if (!!TotalTaxAmount && TotalTaxAmount != 0)
                        $("#TotalTaxAmount").text(toDecimal(TotalTaxAmount));
                    if (!!TotalCAmount && TotalCAmount != 0)
                        $("#TotalCAmount").text(toDecimal(TotalCAmount));
                    if (!!TotalAmount && TotalAmount != 0)
                        $("#TotalAmount").text(toDecimal(TotalAmount));
                    $("#bottomField").attr("hidden", "hidden")
                    $(".form-control").attr("disabled", "disabled");
                    $(".BassClass").attr("disabled", "disabled");
                    $('#1 .ui-icon-ellipsis').hide();
                }
            });
        } else {
            $(".jqgrid-rownum").Contextmenu();
            $(".jqgrid-rownum").mouseover(function () { Index = $(this).parent().attr("id"); console.log(Index); });
        }
    }
    //加载明细
    function GetOrderEntryGrid() {
        var $grid = $("#gridTable");
        $grid.jqGrid({
            unwritten: false,
            datatype: "local",
            height: '100%',
            autowidth: true,
            colModel: [
                { label: '主键', name: 'OrderEntryId', hidden: true },
                { label: '物品名称', name: "ProductName", width: 260, align: 'center', sortable: false, resizable: false },
                { label: '物品编号', name: "ProductCode", width: 100, align: 'center', sortable: false, resizable: false },
                { label: '品牌', name: "Brand", width: 100, align: 'center', sortable: false, resizable: false },
                { label: '规格型号', name: "ModelNo", width: 100, align: 'center', sortable: false, resizable: false },
                {
                    label: '单位', name: 'Unit', width: 100, align: 'center', sortable: false, resizable: false,
                    formatter: function (cellvalue, options, rowObject) {
                        debugger;
                        return top.clientdataItem.CalUnit[cellvalue] == null ? cellvalue : top.clientdataItem.CalUnit[cellvalue];
                    }
                },
                { label: '用途', name: 'Usememo', width: 110, align: 'center', sortable: false, resizable: false },
                { label: '到期日期', name: 'OverdueDate', width: 100, align: 'center', sortable: false, resizable: false },
                { label: '数量', name: 'Qty', width: 80, align: 'center', sortable: false, resizable: false },
                { label: '含税单价', name: 'TaxUnitPrice', width: 80, align: 'center', sortable: false, resizable: false },
                { label: '税率&#37;', name: 'Tax', width: 80, align: 'center', sortable: false, resizable: false },
                { label: '不含税单价', name: 'Price', width: 80, align: 'center', sortable: false, resizable: false },
                { label: '含税金额', name: 'TaxAmount', width: 80, align: 'center', sortable: false, resizable: false },
                { label: '税金', name: 'CAmount', width: 80, align: 'center', sortable: false, resizable: false },
                { label: '不含税金额', name: 'Amount', width: 80, align: 'center', sortable: false, resizable: false },
                { label: '说明信息', name: 'Description', width: 200, align: 'center', sortable: false, resizable: false }

            ],
            hidegrid: false,
            pager: false,
            rownumbers: true,
            shrinkToFit: true,
            gridview: true,
            footerrow: true,
            gridComplete: function () {
                $('#1 .ui-icon-ellipsis').show();
                //合计
                $(this).footerData("set", {
                    "OverdueDate": "合计：",
                    "Qty": "<span id='TotalQty'>0.00</span>",
                    "TaxAmount": "<span id='TotalTaxAmount'>0.00</span>",
                    "CAmount": "<span id='TotalCAmount'>0.00</span>",
                    "Amount": "<span id='TotalAmount'>0.00</span>",
                });
                $('table.ui-jqgrid-ftable td[aria-describedby="gridTable_OverdueDate"]').prevUntil().css("border-right-color", "#fff");
            }
        });
        //表头合并
        $grid.jqGrid('setGroupHeaders', {

            useColSpanStyle: true,
            groupHeaders: [
              { startColumnName: 'ProductName', numberOfColumns: 7, titleText: '商品信息' },
              { startColumnName: 'Qty', numberOfColumns: 7, titleText: '价格信息' }
            ]
        });
        //默认添加8行 空行
        for (var i = 1; i <= 8; i++) {
            var rowdata = {
                OrderEntryId: '<input name="OrderEntryId" type="text" />',
                ProductName: '<div class="product"><input name="ProductName" readonly type="text" class="editable" isvalid="no" checkexpession="NotNull"/><span class="ui-icon-ellipsis"></span></div>',
                ProductCode: '<input name="ProductCode" type="text" class="editable center disabled" /><input name="ProductId" type="hidden" />',
                Brand: '<input name="Brand" type="text" class="editable center disabled" />',
                ModelNo: '<input name="ModelNo" type="text" class="editable center disabled" />',
                Unit: '<input name="Unit" type="text" class="editable center disabled" />',
                Usememo: '<input name="Usememo" type="text" class="editable center BassClass " />',
                OverdueDate: '<input name="OverdueDate" type="text" class="editable form-control input-wdatepicker BassClass" onfocus="WdatePicker()" />',
                TaxUnitPrice: '<input name="TaxUnitPrice" type="number" class="editable center decimal BassClass" isvalid="no" checkexpession="Double" />',
                Tax: '<input name="Tax" type="number" class="editable center decimal BassClass " isvalid="no" checkexpession="Double" />',
                Price: '<input name="Price" type="text" class="editable center decimal disabled" isvalid="no" checkexpession="Double" />',
                Qty: '<input name="Qty" type="number" class="editable center decimal BassClass" isvalid="no" checkexpession="Double" />',
                CAmount: '<input name="CAmount" type="text" class="editable center decimal disabled" isvalid="no" checkexpession="Double" />',
                Amount: '<input name="Amount" type="text" class="editable center decimal disabled" isvalid="no" checkexpession="Double" />',
                TaxAmount: '<input name="TaxAmount" type="text" class="editable center decimal disabled" isvalid="no" checkexpession="Double" />',
                Description: '<input name="Description" type="text" class="editable center BassClass" />',
            }
            $grid.jqGrid('addRowData', i, rowdata);
        };
        $grid.find('.decimal').attr('onfocus', 'IsMoney(this.id)');
        $grid.find('input').attr("disabled", "disabled");
        $grid.find("tbody tr:eq(1)").find('input').removeAttr('disabled').attr("isvalid", "yes");
        $grid.find('.disabled').attr("disabled", "disabled");
        //商品名称事件
        $('input[name="ProductName"]').focus(function () {
            NameFocus($(this));
        });
        //选择商品事件
        $('.ui-icon-ellipsis').click(function () {
            SelectProduct($(this));
        });
        //价格文本框事件
        $grid.find('.decimal').click(function () {
            DecimalSelect($(this));
        });
        //价格文本框换算
        $("#gridTable").find('.decimal').attr("onpropertychange", "Conversion(this)").attr("oninput", "Conversion(this)");
    }
    //保存表单
    function AcceptClick(callback) {
        if (!$('#form1').Validform()) {
            return false;
        }
        var OrderEntryJson = [];
        var OK = false;
        debugger;
        $("#gridTable").find('[role=row]').each(function (i) {
            if (!!$(this).find('input[name="ProductId"]').val()) {
                //if ($(this).find('input[name="OverdueDate"]').val() == "") {
                //    top.dialogTop('到期日期存在空值', 'error');
                //    OK = true;
                //}
                if (isNaN(parseInt($(this).find('input[name="Qty"]').val())) || parseInt($(this).find('input[name="Qty"]').val()) == 0) {
                    top.dialogTop('入仓数量存在空值', 'error');
                    OK = true;
                }
                if (isNaN(parseInt($(this).find('input[name="TaxUnitPrice"]').val())) || parseInt($(this).find('input[name="TaxUnitPrice"]').val()) == 0) {
                    top.dialogTop('单价存在空值', 'error');
                    OK = true;
                }
                OrderEntryJson.push({
                    Id: "",
                    Type: 1,
                    BillId: "",
                    EnabledMark: 1,
                    Name: $(this).find('input[name="ProductName"]').val(),
                    Code: $(this).find('input[name="ProductCode"]').val(),
                    ProductId: $(this).find('input[name="ProductId"]').val(),
                    ModelNo: $(this).find('input[name="ModelNo"]').val(),
                    Brand: $(this).find('input[name="Brand"]').val(),
                    Unit: $(this).find('input[name="Unit"]').val(),
                    Tax: parseInt($(this).find('input[name="Tax"]').val()),
                    Num: parseInt($(this).find('input[name="Qty"]').val()),
                    OverdueDate: $(this).find('input[name="OverdueDate"]').val(),
                    UseMemo: $(this).find('input[name="Usememo"]').val(),
                    Price: parseFloat($(this).find('input[name="TaxAmount"]').val()),
                    UnitPrice: parseFloat($(this).find('input[name="TaxUnitPrice"]').val()),
                    Description: $(this).find('input[name="Description"]').val(),

                });
            }
        });
        var postData = $("#form1").GetWebControls(keyValue);
        postData["VendorId"] = $("#Vendor").attr("title");
        postData["SettlementUserId"] = $("#SettlementUserName").attr("title");
        postData["SignUserId"] = $("#SignUserName").attr("title");
        postData["CheckUserId"] = $("#CheckUserName").attr("title");
        postData["TypeName"] = TypeName;
        postData["orderEntryJson"] = JSON.stringify(OrderEntryJson);
        postData["OrganizeId"] = _organizeid;
        if (OK) return false;
        $.ConfirmAjax({
            msg: "注：您确认要保存此操作吗？",
            url: "../../ResourceManage/RS_ProductIn/SaveForm?keyValue=" + keyValue,
            param: { queryJson: JSON.stringify(postData) },
            success: function (data) {
                // $("#save").attr("disabled", "disabled");
                location.reload();
            }
        });
    }
    //添加行
    function li_AddRow() {
        var rowdata = {
            OrderEntryId: '<input name="OrderEntryId" type="text" />',
            ProductName: '<div class="product"><input name="ProductName" readonly type="text" class="editable" isvalid="no" checkexpession="NotNull"/><span class="ui-icon-ellipsis"></span></div>',
            ProductCode: '<input name="ProductCode" type="text" class="editable center disabled" disabled="disabled"/><input name="ProductId" type="hidden" />',
            Brand: '<input name="Brand" type="text" class="editable center disabled" disabled="disabled"/>',
            ModelNo: '<input name="ModelNo" type="text" class="editable center disabled" disabled="disabled"/>',
            Unit: '<input name="Unit" type="text" class="editable center disabled" disabled="disabled"/>',
            Usememo: '<input name="Usememo" type="text" class="editable center BassClass " />',
            OverdueDate: '<input name="OverdueDate" type="text" class="editable form-control input-wdatepicker BassClass" onfocus="WdatePicker()" />',
            TaxUnitPrice: '<input name="TaxUnitPrice" type="number" class="editable center decimal BassClass"  isvalid="no" checkexpession="Double" onfocus="IsMoney(this.id)" />',
            Tax: '<input name="Tax" type="number" class="editable center decimal BassClass "  isvalid="no" checkexpession="Double" onfocus="IsMoney(this.id)" />',
            Price: '<input name="Price" type="text" class="editable center decimal disabled" disabled="disabled" isvalid="no" checkexpession="Double" onfocus="IsMoney(this.id)" />',
            Qty: '<input name="Qty" type="number" class="editable center decimal BassClass"  isvalid="no" checkexpession="Double" onfocus="IsMoney(this.id)" />',
            CAmount: '<input name="CAmount" type="text" class="editable center decimal disabled"  disabled="disabled" isvalid="no" checkexpession="Double" onfocus="IsMoney(this.id)" />',
            Amount: '<input name="Amount" type="text" class="editable center decimal disabled"  disabled="disabled" isvalid="no" checkexpession="Double" onfocus="IsMoney(this.id)" />',
            TaxAmount: '<input name="TaxAmount" type="text" class="editable center decimal disabled"  isvalid="no" checkexpession="Double" onfocus="IsMoney(this.id)" />',
            Description: '<input name="Description" type="text" class="editable center BassClass" />',
        }
        var ids = $("#gridTable").getDataIDs();
        var Index = parseInt(ids[ids.length - 1]) + 1;
        $("#gridTable").jqGrid('addRowData', Index, rowdata);
        $(".jqgrid-rownum").last().Contextmenu();
        $(".jqgrid-rownum").last().mouseover(function () { Index = $(this).parent().attr("id"); });
        //商品名称事件
        $('input[name="ProductName"]').last().focus(function () {
            NameFocus($(this));
        });
        //选择商品事件
        $('.ui-icon-ellipsis').last().click(function () {
            SelectProduct($(this));
        });
        //价格文本框事件
        $("#gridTable").find("tr").last().find('.decimal').click(function () {
            DecimalSelect($(this));
        });
        $("#gridTable").find("tr").last().find('.decimal').attr("onpropertychange", "Conversion(this)").attr("oninput", "Conversion(this)");
    }
    //删除行
    function li_Del() {
        var ids = $("#gridTable").getDataIDs();
        var Index = ids[ids.length - 1];
        $("#gridTable").delRowData(Index);
    }
    //删除指定行
    function li_DelData(rowid) {
        if (!!rowid) Index = rowid;
        $("#gridTable").delRowData(Index);
        $('.ui-icon-ellipsis').hide()
        $("#gridTable tr:eq(1) .ui-icon-ellipsis").show().next().removeAttr('disabled');
        $("#gridTable tr:eq(1)").find('.decimal').keyup();
        if ($("#gridTable").jqGrid("getRowData").length < 8) {
            li_AddRow();
        }
    }
    //词典
    function GetDataSelect(Type) {
        var options = {};
        options["TopForm"] = "Tab";
        switch (Type) {
            case 1: //供应商
                options["type"] = 6;
                options["data"] = [{ "id": "Vendor" }];
                options["organizeid"] = '@LeSoft.Application.Code.OperatorProvider.Provider.Current().CompanyId';
                break;
            case 2:
                options["type"] = 3;
                options["data"] = [{ "id": "CheckUserName" }];
                options["organizeid"] = '@LeSoft.Application.Code.OperatorProvider.Provider.Current().CompanyId';
                break;
            case 3:
                options["type"] = 3;
                options["data"] = [{ "id": "SettlementUserName" }];
                options["organizeid"] = '@LeSoft.Application.Code.OperatorProvider.Provider.Current().CompanyId';
                break;
            case 4:
                options["type"] = 3;
                options["data"] = [{ "id": "SignUserName" }];
                options["organizeid"] = '@LeSoft.Application.Code.OperatorProvider.Provider.Current().CompanyId';
                break;
            default:

        }
        DataItemClick(JSON.stringify(options));
    }

    //商品名称事件
    function NameFocus($this) {
        $('.ui-icon-ellipsis').hide();
        $this.next('.ui-icon-ellipsis').show();
    }
    //选择商品事件
    function SelectProduct($this) {
        if (keyValue != "") {
            return false;
        }
        var $ellipsis = $this;
        dialogOpen({
            id: "BillProductForm",
            title: '选择商品',
            url: '/ResourceManage/RS_Product/BillProductForm?Type=2',
            width: "1100px",
            height: "700px",
            callBack: function (iframeId) {
                top.frames[iframeId].AcceptClick(function (data) {
                    for (var i = 1; i <= data.length; i++) {
                        if ($("#gridTable").find('[role=row]').find('[data-value=' + data[i - 1].Id + ']').length == 0) {
                            var tds = $("#gridTable").find('[role=row]').find('input[name="ProductName"]');
                            if (i != 1) {
                                for (var j = 0; j < tds.length; j++) {
                                    if (!$(tds[j]).val()) {
                                        $ellipsis = $(tds[j]);
                                        break;
                                    }
                                }
                            }
                            Index = $ellipsis.parent().parent().parent().attr("id");
                            $ellipsis.parents('[role=row]').find('input[name="ProductName"]').val(data[i - 1].Name).css("padding-left", "20px").parent().append("<i class=\"fa fa-trash-o\" style=\"display: inline;cursor:pointer;position:absolute;left:5px;top:30%;\" onclick='li_DelData(" + Index + ")'></i>");
                            $ellipsis.parents('[role=row]').find('input[name="ProductCode"]').val(data[i - 1].Code).attr('data-value', data[i - 1].Id);
                            $ellipsis.parents('[role=row]').find('input[name="ProductId"]').val(data[i - 1].Id);
                            $ellipsis.parents('[role=row]').find('input[name="Brand"]').val(data[i - 1].Brand);
                            $ellipsis.parents('[role=row]').find('input[name="ModelNo"]').val(data[i - 1].ModelNo);
                            $ellipsis.parents('[role=row]').find('input[name="Unit"]').val(data[i - 1].Unit);
                            $ellipsis.parents('[role=row]').find('input[name="TaxUnitPrice"]').val('0.00');
                            $ellipsis.parents('[role=row]').find('input[name="Tax"]').val('0.00');
                            $ellipsis.parents('[role=row]').find('input[name="Price"]').val('0.00');
                            $ellipsis.parents('[role=row]').find('input[name="Qty"]').val('1.00');
                            $ellipsis.parents('[role=row]').find('input[name="CAmount"]').val('0.00');
                            $ellipsis.parents('[role=row]').find('input[name="TaxAmount"]').val('0.00');
                            $ellipsis.parents('[role=row]').find('input[name="Amount"]').val('0.00');
                            $ellipsis.parents('[role=row]').find('input[name="Description"]').val("");
                            $ellipsis.parents('[role=row]').find('input.BassClass').removeAttr('disabled').attr("isvalid", "yes");
                            if (!!$(tds[tds.length - 1]).val())
                                li_AddRow();
                            $ellipsis.parents('[role=row]').next().find('input.BassClass').removeAttr('disabled');
                            $('.ui-icon-ellipsis').hide();
                            $ellipsis.parents('[role=row]').next().find('input[name="ProductName"]').removeAttr("disabled").next('.ui-icon-ellipsis').show();
                        } else {
                            top.dialogTop('商品信息已存在,不能重复添加', 'error');
                        }
                    }
                });
            },
            btn: ['选择', '关闭']
        });
    }

    //价格文本框事件
    function DecimalSelect($this) {
        $this.select();
    }

    //价格文本框换算
    function Conversion(obj) {
        $this = $(obj);
        var _inputName = $this.attr('name');
        var $Qty = $this.parents('[role=row]').find('input[name="Qty"]');                    //数量
        var $TaxUnitPrice = $this.parents('[role=row]').find('input[name="TaxUnitPrice"]');  //含税单价
        var $Tax = $this.parents('[role=row]').find('input[name="Tax"]');                    //税率(%)
        var $Price = $this.parents('[role=row]').find('input[name="Price"]');                //不含税单价
        var $TaxAmount = $this.parents('[role=row]').find('input[name="TaxAmount"]');        //含税金额
        var $CAmount = $this.parents('[role=row]').find('input[name="CAmount"]');            //税金
        var $Amount = $this.parents('[role=row]').find('input[name="Amount"]');              //不含税金额
        if ($Tax.val() > 100 || $Tax.val() < 0) {
            $Tax.val(0);
            $Tax = $this.parents('[role=row]').find('input[name="Tax"]');
        }
        if ($TaxUnitPrice.val() < 0) {
            $TaxUnitPrice.val(0);
            $TaxUnitPrice = $this.parents('[role=row]').find('input[name="Tax"]');
        }
        //含税单价/1+税率=不含税单价
        $Price.val(isNaN($Qty) ? toDecimal($TaxUnitPrice.val() / (1 + ($Tax.val() / 100))) : "");
        //数量*单价=不含税金额
        $Amount.val(toDecimal($Qty.val() * $TaxUnitPrice.val() / (1 + ($Tax.val() / 100))));
        //数量*含税单价=含税金额
        $TaxAmount.val(toDecimal($Qty.val() * $TaxUnitPrice.val()));
        //含税金额-不含税金额=税金
        $CAmount.val(toDecimal(($TaxAmount.val() - $Amount.val())));
        //合计
        var TotalQty = 0.00, TotalAmount = 0.00, TotalCAmount = 0.00, TotalTaxAmount = 0.00;
        $("#gridTable").find("tbody tr").each(function (i) {
            //数量合计
            var Qty = $(this).find('td:eq(9)').find('input').val();
            if (Qty != "" && Qty != undefined) {
                TotalQty += Number(Qty);
            }
            //含税金额合计
            var TaxAmount = $(this).find('td:eq(13)').find('input').val();
            if (TaxAmount != "" && TaxAmount != undefined) {
                TotalTaxAmount += Number(TaxAmount);
            }
            //税金合计
            var CAmount = $(this).find('td:eq(14)').find('input').val();
            if (CAmount != "" && CAmount != undefined) {
                TotalCAmount += Number(CAmount);
            }
            //不含税金额合计
            var Amount = $(this).find('td:eq(15)').find('input').val();
            if (Amount != "" && Amount != undefined) {
                TotalAmount += Number(Amount);
            }
        });
        $("#TotalQty").text(toDecimal(TotalQty));
        $("#TotalTaxAmount").text(toDecimal(TotalTaxAmount));
        $("#TotalCAmount").text(toDecimal(TotalCAmount));
        $("#TotalAmount").text(toDecimal(TotalAmount));
    }
</script>
<div class="bills">
    <table class="form" style="width: 100%; margin-bottom: 10px;">
        <tr>
            <th class="formTitle">仓库名称<font face="宋体">*</font></th>
            <td class="formValue">
                <div id="WarehouseId" type="select" class="ui-select BassClass" isvalid="yes" checkexpession="NotNull"></div>
            </td>
            <th class="formTitle">入仓类别<font face="宋体">*</font></th>
            <td class="formValue">
                <div id="Type" type="selectTree" class="ui-select BassClass" isvalid="yes" checkexpession="NotNull"></div>
            </td>
            <th class="formTitle">单据日期<font face="宋体">*</font></th>
            <td class="formValue">
                <input id="Date" type="text" value="@LeSoft.Util.Time.GetToday()" class="form-control input-wdatepicker BassClass" onfocus="WdatePicker({maxDate:'%y-%M-%d'})" isvalid="yes" checkexpession="NotNull" />
            </td>
            <th class="formTitle">单据编号<font face="宋体">*</font></th>
            <td class="formValue">
                <input id="Code" type="text" placeholder="单据编号由系统自动生成" class="form-control BassClass" />
            </td>
        </tr>
        <tr>

            <th class="formTitle">供&nbsp;应&nbsp;商</th>
            <td class="formValue">
                <div class="input-group" style="width: 100%;">
                    <input id="Vendor" type="text" class="form-control  BaseClass">
                    <span class="input-group-btn">
                        <a onclick="GetDataSelect(1)" class="form-control  BaseClass" style="cursor: pointer"><i class="fa fa fa-book BaseClass  " style=" font-size: 20px; padding-right: 5px;   color: gray"></i></a>
                    </span>
                </div>
            </td>
            <th class="formTitle"> 是否验收<font face="宋体">*</font></th>
            <td class="formValue">
                <div id="IsCheck" type="selectTree" class="ui-select BassClass" isvalid="yes" checkexpession="NotNull"></div>
            </td>
            <th class="formTitle"> 是否结算<font face="宋体">*</font></th>
            <td class="formValue">
                <div id="IsSettlement" type="selectTree" class="ui-select BassClass" isvalid="yes" checkexpession="NotNull"></div>
            </td>
            <th class="formTitle"> 是否签名<font face="宋体">*</font></th>
            <td class="formValue">
                <div id="IsSign" type="selectTree" class="ui-select BassClass" isvalid="yes" checkexpession="NotNull"></div>
            </td>
        </tr>
        <tr>
            <td class="formValue" colspan="8" id="Audit"></td>
        </tr>
    </table>
    <div class="gridPanel">
        <table id="gridTable"></table>
    </div>

    <textarea id="Description" placeholder="暂无备注信息" class="form-control BassClass" style="width: 100%; height: 50px; margin-top: 10px;"></textarea>
    <table class="form" style="width: 100%; margin-top: 5px;">

        <tr>

            <th class="formTitle">采购订单号<font face="宋体">*</font></th>
            <td class="formValue">
                <input id="SourceId" type="text" class="form-control BassClass" isvalid="yes" checkexpession="NotNull" />
            </td>
            <th class="formTitle">制单人员<font face="宋体">*</font></th>
            <td class="formValue">
                <input id="CreateUserName" type="text" class="form-control BassClass" readonly value="@LeSoft.Application.Code.OperatorProvider.Provider.Current().UserName" />
            </td>
            <th class="formTitle">发&nbsp;票&nbsp;类&nbsp;型</th>
            <td class="formValue">
                <div id="InvoiceType" type="selectTree" class="ui-select BassClass"></div>
            </td>
            <th class="formTitle">发票号</th>
            <td class="formValue">
                <input id="InvoiceNo" type="text" class="form-control BassClass" />
            </td>

        </tr>
        <tr>

            <th class="formTitle CS_Check" hidden>收据号<font face="宋体">*</font></th>
            <td class="formValue CS_Check" hidden>
                <input id="ReceiptNo" type="text" class="form-control BassClass" />
            </td>
            <th class="formTitle CS_Check" hidden>验收人<font face="宋体">*</font></th>
            <td class="formValue CS_Check" hidden>
                <div class="input-group" style="width: 100%;">
                    <input id="CheckUserName" type="text" class="form-control  BaseClass">
                    <span class="input-group-btn">
                        <a onclick="GetDataSelect(2)" class="form-control  BaseClass" style="cursor: pointer"><i class="fa fa fa-book BaseClass  " style=" font-size: 20px; padding-right: 5px;   color: gray"></i></a>
                    </span>
                </div>
            </td>

            <th class="formTitle CS_Check" hidden>验收日期<font face="宋体">*</font></th>
            <td class="formValue CS_Check" hidden>
                <input id="CheckDate" type="text" value="@LeSoft.Util.Time.GetToday()" class="form-control input-wdatepicker BassClass" onfocus="WdatePicker({maxDate:'%y-%M-%d'})" isvalid="yes" checkexpession="NotNull" />
            </td>
            <th class="formTitle CS_Settlement" hidden>结算单号<font face="宋体">*</font></th>
            <td class="formValue CS_Settlement" hidden>
                <input id="SettlementBillId" type="text" class="form-control BassClass" />
            </td>

        </tr>
        <tr>
            <th class="formTitle CS_Settlement" hidden>结算人<font face="宋体">*</font></th>
            <td class="formValue CS_Settlement" hidden>
                <div class="input-group" style="width: 100%;">
                    <input id="SettlementUserName" type="text" class="form-control  BaseClass">
                    <span class="input-group-btn">
                        <a onclick="GetDataSelect(3)" class="form-control  BaseClass" style="cursor: pointer"><i class="fa fa fa-book BaseClass  " style=" font-size: 20px; padding-right: 5px;   color: gray"></i></a>
                    </span>
                </div>
            </td>

            <th class="formTitle CS_Settlement" hidden>结算日期<font face="宋体">*</font></th>
            <td class="formValue CS_Settlement" hidden>
                <input id="SettlementDate" type="text" value="@LeSoft.Util.Time.GetToday()" class="form-control input-wdatepicker BassClass" onfocus="WdatePicker({maxDate:'%y-%M-%d'})" isvalid="yes" checkexpession="NotNull" />
            </td>
            <th class="formTitle CS_Sign" hidden>主管名称<font face="宋体">*</font></th>
            <td class="formValue CS_Sign" hidden>
                <div class="input-group" style="width: 100%;">
                    <input id="SignUserName" type="text" class="form-control  BaseClass">
                    <span class="input-group-btn">
                        <a onclick="GetDataSelect(4)" class="form-control  BaseClass" style="cursor: pointer"><i class="fa fa fa-book BaseClass  " style=" font-size: 20px; padding-right: 5px;   color: gray"></i></a>
                    </span>
                </div>
            </td>
            <th class="formTitle CS_Sign" hidden>签名日期</th>
            <td class="formValue CS_Sign" hidden>
                <input id="SignDate" type="text" value="@LeSoft.Util.Time.GetToday()" class="form-control input-wdatepicker BassClass" onfocus="WdatePicker({maxDate:'%y-%M-%d'})" />
            </td>
        </tr>

    </table>
</div>
<div id="bottomField">
    @*<a id="savaAndAdd" class="btn btn-success" onclick="AcceptClick(1)">保存并新增</a>*@
    <a id="save" class="btn btn-default" onclick="AcceptClick(2)">保存单据</a>
</div>
<div class="contextmenu">
    <ul>
        <li onclick="li_DelData()">删除该行</li>
        <li onclick="li_AddRow()">添加一行</li>
        <li onclick="li_Del()">删除一行</li>
    </ul>
</div>
